    //
//  ShortAnswerPageViewController.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/2/15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ShortAnswerPageViewController.h"
#import "AD_Image.h"
#import "AD_Page.h"
#import "AD_TextBox.h"
#import "AD_Button.h"
#import "GDataXMLNode.h"

UIButton *submitButton;

@implementation ShortAnswerPageViewController
@synthesize BGImage,TW_NewText;
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    BGImage.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:pageOB.imageBG]];
    
    [self addImage];


    NSLog(@"Count: %d", [pageOB.mut_Arr_TextBox count]);
	
	NSLog(@"enumerator created");
	AD_TextBox *textBox = [pageOB.mut_Arr_TextBox objectAtIndex:0];
	NSLog(@"textbox declared");

	NSLog(@"The object is: %@", textBox);
	CGRect viewRect = CGRectMake((float)textBox.left, (float)textBox.top, (float)textBox.width, (float)textBox.height);
	NSLog(@"The Rect is complete");
	
	//UITextField *newTextField = [[UITextField alloc] initWithFrame:viewRect];
	TW_NewText = [[UITextView alloc] initWithFrame:viewRect];
    TW_NewText.delegate = self;
	TW_NewText.backgroundColor = [[UIColor alloc] initWithWhite: 0.3f alpha: 0.7f];
	TW_NewText.textColor = [UIColor whiteColor];
	UIFont * newFont = [TW_NewText.font fontWithSize:textBox.fontSize];
	TW_NewText.font = newFont;
	NSLog(@"The newTextView is created");	

	//[newTextField setFrame:viewRect];
	
	//newTextView.alpha = 1.0;
	
	//newTextView.backgroundColor = [UIColor redColor];
	NSLog(@"newTextView created: %@", TW_NewText);
	[self.view addSubview:TW_NewText];
	
	NSLog(@"newTextView added: %@", TW_NewText);
	//[newTextView sizeToFit];

	
	//Add a button
	NSLog(@"Button Count: %d", [pageOB.mut_Arr_Button count]);
	for (int i=0; i < [pageOB.mut_Arr_Button count]; i++) {
		AD_Button *theButton = (AD_Button*)[pageOB.mut_Arr_Button objectAtIndex:i];
		NSLog(@"The button is: %@", theButton);
		UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
		//Normal
		UIImage *normalImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:theButton.imageOff]];
		[newButton setImage:normalImage forState:UIControlStateNormal];
		//Selected
		UIImage *selectedImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:theButton.imageOn]];
		[newButton setImage:selectedImage forState:UIControlStateSelected];
		
		CGRect buttonRect = CGRectMake((float)theButton.left, (float)theButton.top, (float)theButton.width, (float)theButton.height);
		[newButton setFrame:buttonRect];
		
		newButton.tag = i;
		[newButton addTarget:self action:@selector(buttonPush:) forControlEvents:UIControlEventTouchUpInside];
		[self.view addSubview:newButton];
		submitButton = newButton;
	}

	//Give the textView focus
	[TW_NewText becomeFirstResponder];
    [super viewDidLoad];
}


-(void)buttonPush:(id)sender{
	UIButton *theButton = (UIButton*)sender;
	AD_Button *buttonConfig = (AD_Button*)[pageOB.mut_Arr_Button objectAtIndex:theButton.tag];
	
//	NSLog(@"Button Type: %@ ; Button Section: %d", buttonConfig.buttonType , buttonConfig.section);
	submitButton.enabled = NO;
	
	//Close the keyboard
	[TW_NewText resignFirstResponder];
	
    for(AD_Action* action in buttonConfig.actions){
        if([action isKindOfClass:[Action_Submit class]]){
            [self appendUserData:[self BuildXmlData]];
            [self submitUserData];
            TW_NewText.userInteractionEnabled = NO;
            NSLog(@"Submit the user data");
        } else if ([action isKindOfClass:[Action_Next class]]) {
            NSLog(@"Go to the next page");
            [self appendUserData:[self BuildXmlData]];
            if(pageOB.grade.hasInstantFeedback){
                [self addInstantFeedback];
            } else {
                [self loadNextPage];
            }
        } else if ([action isKindOfClass:[Action_GoTo class]]) {
            Action_GoTo* gt = (Action_GoTo*)action;
            NSLog(@"Go To Special Session");
            [self appendUserData:[self BuildXmlData]];
            [self GoToSection:gt.section
                    NewPageID:gt.page];
        }else if ([action isKindOfClass:[Action_Save class]]){
            NSLog(@"Save Button Pressed");
            
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            NSString *ACTIVEDECKSAVEKEY = [NSString stringWithFormat:@"Value(%d)", pageOB.pageID];
            
            [prefs setObject:TW_NewText.text forKey:ACTIVEDECKSAVEKEY];
            NSLog(@"Value(%d) saved", pageOB.pageID);
            
            [prefs synchronize];
            [self loadNextPage];
            
        }
    }
    
//	//Switch based on the action
//	if ([buttonConfig.buttonType isEqualToString:@"Submit"]) {
//		[self appendUserData:[self BuildXmlData]];
//		[self submitUserData];
//		TW_NewText.userInteractionEnabled = NO;
//		NSLog(@"Submit the user data");
//	} else if ([buttonConfig.buttonType isEqualToString:@"Next"]) {
//		NSLog(@"Go to the next page");
//		[self appendUserData:[self BuildXmlData]];
//        if(pageOB.grade.hasInstantFeedback){
//            [self addInstantFeedback];
//        } else {
//            [self loadNextPage];
//        }
//	} else if ([buttonConfig.buttonType isEqualToString:@"GoTo"]) {
//        NSLog(@"Go To Special Session");
//        [self appendUserData:[self BuildXmlData]];
//        [self GoToSection:buttonConfig.section
//                NewPageID:buttonConfig.page];
//    }else if ([buttonConfig.buttonType isEqualToString:@"Save"]){
//        NSLog(@"Save Button Pressed");
//        
//        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//        NSString *ACTIVEDECKSAVEKEY = [NSString stringWithFormat:@"Value(%d)", pageOB.pageID];
//        
//        [prefs setObject:TW_NewText.text forKey:ACTIVEDECKSAVEKEY];
//        NSLog(@"Value(%d) saved", pageOB.pageID);
//        
//        [prefs synchronize];
//        [self loadNextPage];
//
//    }
	
}

- (GDataXMLElement *)BuildXmlData
{
	GDataXMLElement *answerElement = [GDataXMLElement elementWithName:@"Answer"];
	GDataXMLNode *Type = [GDataXMLNode attributeWithName:@"Type" stringValue:@"ShortAnswer"];
	GDataXMLNode *Page = [GDataXMLNode attributeWithName:@"Page" stringValue:[NSString stringWithFormat:@"%d",pageOB.pageID]];
    
    GDataXMLNode *Text = [GDataXMLNode attributeWithName:@"Text" stringValue:TW_NewText.text];
	[answerElement addChild:Type];
	[answerElement addChild:Page];
	[answerElement addChild:Text];
	
    
	return answerElement;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {	
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



- (void)dealloc {
    [BGImage release];
    [TW_NewText release];
    [super dealloc];
}


@end
